package com.yunkaweilai.android.fragment.member;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.member.MemberInfoListActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.jici.CommonMemberModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberLevelModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

public class CommonMemberFragmentMember extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    Unbinder unbinder;
    @BindView(R.id.id_listView)
    ListView idListView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView id_multipleStatusView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_tv_num)
    TextView idTvNum;
    @BindView(R.id.line_checkbox)
    LinearLayout lineCheck;
    @BindView(R.id.id_tv_all)
    TextView idTvAll;
    @BindView(R.id.group_member_rbtn_all)
    CheckBox checkBox;
    private int mpage1 = 1;
    private boolean mHasMore;
    private ArrayList<MemberHeadModel> memberList = new ArrayList<>();
    private ArrayList<MemberLevelModel.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<MemberHeadModel> adapter;
    private String id = "";
    private TextView idTvAllMember;
    private String num = "";

    public static CommonMemberFragmentMember getInstentce(String id, TextView textView) {
        CommonMemberFragmentMember fragment = new CommonMemberFragmentMember();
        fragment.id = id;
        fragment.idTvAllMember = textView;
        return fragment;
    }

    //Fragment的View加载完毕的标记
    private boolean isLoading = false;
    //Fragment对用户可见的标记
    private boolean isUIVisible;
    //setUserVisibleHint和lazyLoad两个方法是为了去除viewPager+fragment的懒加载


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            isUIVisible = true;

            lazyLoad();//调用下面的方法
        } else {
            isUIVisible = false;
        }
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (!isLoading && isUIVisible) {
//            loadInfo();//加载数据的方法
            initHttp(true);
            //数据加载完毕,恢复标记,防止重复加载
//            isLoading = true;
            isUIVisible = false;
        } else {
//            Log.d(TAG, "lazyLoad: "+ num);
//            idTvNum.setText("共" + num + "个会员");
        }
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView, this, true);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initAdapter();
        initclick();
    }


    @Override
    public int getContentViewId() {
        return R.layout.fragment_list_for_member;
    }

    //todo:k 新建step5
    private void initclick() {
        lineCheck.setVisibility(View.VISIBLE);
        idTvAll.setVisibility(View.GONE);
        checkBox.setVisibility(View.GONE);
        idTvNum.setText("共" + "..." + "个会员");
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (BaseApplication.getAppRuleModel().isIs_super() || BaseApplication.getAppRuleModel().getApp_rule().get("17")) {
                    MemberInfoListActivity.actionStart(mAc, memberList.get(position), "1");
                }
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void initAdapter() {
        adapter = new CommonAdapter<MemberHeadModel>(mAc, R.layout.item_list_member, memberList) {
            @Override
            protected void convert(ViewHolder viewHolder, MemberHeadModel item, int position) {
                ImageView idImgHead = viewHolder.getView(R.id.id_img_head);
                Utils.MemberHeadImg(mAc, item.getMember_avatar(), item.getMember_sex(), idImgHead);
                TextView idTvName = viewHolder.getView(R.id.id_tv_name);
                //设置名字、手机和状态
                if (item.getStatus_info().is_valid()) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已过期" + "</font>");
                } else if ("2".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已锁定" + "</font>");
                } else if ("3".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='" + getResources().getColor(R.color.calu_red) + "'>" + "已挂失" + "</font>");
                } else {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName);
                }

                viewHolder.setText(R.id.id_tv_level, "等级：" + item.getLevel_name() + "     卡号：" + item.getCard_no());
                viewHolder.setText(R.id.id_tv_discount, "折扣：" + item.getDiscount() / 10 + "折   积分：" + item.getMember_points() + "   余额：" + item.getMember_price());
            }
        };
        idListView.setAdapter(adapter);
    }

    private boolean initHttp(final boolean refresh) {
        mpage1 = refresh ? 1 : mpage1;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        if (id.equals("0")) {
            HttpRequest.postUrl(Api.MEMBER_LIST)
                    .addParams("ShowPage", "1")
                    .addParams("PageSize", "10")
                    .addParams("CurrPage", mpage1 + "")
//                    .addParams("level_id", id)
                    .execute(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            endRefreshOrLoad(refresh);
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {
                                mpage1++;
                                Gson gson = new Gson();
                                CommonMemberModel memberModel = gson.fromJson(json, CommonMemberModel.class);
//                                if (id.equals("0")) {
//                                    idTvAllMember.setText("共" + memberModel.getData().getPage().getCount() + "个会员");
//                                }
                                num = memberModel.getData().getPage().getCount();
                                if (idTvNum != null) {
                                    idTvNum.setText("共" + num + "个会员");
                                }
                                if (refresh) {
                                    memberList.clear();
                                }
                                if (memberModel.getData().getPage().getCount().equals("0")) {
                                    if (id_multipleStatusView != null)
                                        id_multipleStatusView.showEmpty();
                                } else {
                                    if (id_multipleStatusView != null)
                                        id_multipleStatusView.showContent();
                                }
                                if (memberModel.getData().getList() != null && memberModel.getData().getList().size() > 0) {
                                    memberList.addAll(memberModel.getData().getList());
                                    mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                if (id_multipleStatusView != null)
                                    id_multipleStatusView.showError();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            if (id_multipleStatusView != null)
                                id_multipleStatusView.showError();
                        }
                    });
        } else {
            HttpRequest.postUrl(Api.MEMBER_LIST)
                    .addParams("ShowPage", "1")
                    .addParams("PageSize", "10")
                    .addParams("CurrPage", mpage1 + "")
                    .addParams("level_id", id)
                    .addParams("searchtype", "senior")
                    .executeSearchMember(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            endRefreshOrLoad(refresh);
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {
                                mpage1++;
                                Gson gson = new Gson();
                                CommonMemberModel memberModel = gson.fromJson(json, CommonMemberModel.class);
//                                if (id.equals("0")) {
//                                    idTvAllMember.setText("共" + memberModel.getData().getPage().getCount() + "个会员");
//                                }
                                num = memberModel.getData().getPage().getCount();
                                if (idTvNum != null) {
                                    idTvNum.setText("共" + num + "个会员");
                                }
                                if (refresh) {
                                    memberList.clear();
                                }
                                if (memberModel.getData().getPage().getCount().equals("0")) {
                                    if (id_multipleStatusView != null)
                                        id_multipleStatusView.showEmpty();
                                } else {
                                    if (id_multipleStatusView != null)
                                        id_multipleStatusView.showContent();
                                }
                                if (memberModel.getData().getList() != null && memberModel.getData().getList().size() > 0) {
                                    memberList.addAll(memberModel.getData().getList());
                                    mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                if (id_multipleStatusView != null)
                                    id_multipleStatusView.showError();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            if (id_multipleStatusView != null)
                                id_multipleStatusView.showError();
                        }
                    });
        }

        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
